package com.catosist.run.application.viaje;

import com.catosist.run.application.Util.ButtonTabComponent;
import com.catosist.run.application.desktopapplication.DesktopApplication;
import com.catosist.run.application.desktopapplication.DesktopApplicationView;
import com.catosist.run.application.viaje.factura.ManFactura;
import com.catosist.run.application.viaje.gasto.ManGasto;
import com.catosist.run.application.viaje.gestion.GestionViaje;
import com.catosist.run.business.gestorpersona.GestorPersona;
import com.catosist.run.business.gestorruta.GestorRuta;
import com.catosist.run.business.gestorvehiculo.GestorVehiculo;
import com.catosist.run.business.gestorviaje.GestorViaje;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.WindowConstants;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Luizitoh
 */
public class ManViaje extends javax.swing.JFrame {

    /** Creates new form ManPers */
    public ManViaje(GestorViaje gestorViaje) {

        initComponents();
        //viajeDao = new ViajeDao();
        this.gestorViaje = gestorViaje;
//        refresh();
    }

    public ManViaje(DesktopApplicationView runv) {
//        this.viewRun = runv;
        initComponents();
//        refresh();
    }

    public ManViaje(boolean flag) {
        initComponents();
        iniciar();
        gestionViaje = new GestionViaje(gestorViaje);
//        refresh();
    }

    public ManViaje(GestorViaje gestorViaje, GestorRuta gestorRuta, GestorPersona gestorPersona,
            GestorVehiculo gestorVehiculo) {
        this.gestorViaje = gestorViaje;
        this.gestorRuta = gestorRuta;
        this.gestorPersona = gestorPersona;
        this.gestorVehiculo = gestorVehiculo;
        initComponents();
        gestionViaje = new GestionViaje(gestorViaje);
        
//        refresh();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new JPanel();
        jTabbedPane1 = new JTabbedPane();
        jPanel3 = new JPanel();
        btnAgregarViaje = new JButton();
        btnEditViaje = new JButton();
        btnEliminarViaje = new JButton();
        btnBuscarViaje = new JButton();
        btnVerVIiajes = new JButton();
        btnVerGastos = new JButton();
        btnFacturas = new JButton();
        tabWork = new JTabbedPane();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        setName("Formmaviaje"); // NOI18N

        jPanel1.setBorder(BorderFactory.createEtchedBorder());
        jPanel1.setName("jPanel1"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel3.setName("jPanel3"); // NOI18N

        ResourceMap resourceMap = Application.getInstance(DesktopApplication.class).getContext().getResourceMap(ManViaje.class);
        btnAgregarViaje.setText(resourceMap.getString("btnAgregarViaje.text")); // NOI18N
        btnAgregarViaje.setName("btnAgregarViaje"); // NOI18N
        btnAgregarViaje.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnAgregarViajeActionPerformed(evt);
            }
        });

        btnEditViaje.setText(resourceMap.getString("btnEditViaje.text")); // NOI18N
        btnEditViaje.setName("btnEditViaje"); // NOI18N
        btnEditViaje.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnEditViajeActionPerformed(evt);
            }
        });

        btnEliminarViaje.setText(resourceMap.getString("btnEliminarViaje.text")); // NOI18N
        btnEliminarViaje.setName("btnEliminarViaje"); // NOI18N
        btnEliminarViaje.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnEliminarViajeActionPerformed(evt);
            }
        });

        btnBuscarViaje.setText(resourceMap.getString("btnBuscarViaje.text")); // NOI18N
        btnBuscarViaje.setName("btnBuscarViaje"); // NOI18N

        btnVerVIiajes.setText(resourceMap.getString("btnVerVIiajes.text")); // NOI18N
        btnVerVIiajes.setName("btnVerVIiajes"); // NOI18N
        btnVerVIiajes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnVerVIiajesActionPerformed(evt);
            }
        });

        btnVerGastos.setText(resourceMap.getString("btnVerGastos.text")); // NOI18N
        btnVerGastos.setName("btnVerGastos"); // NOI18N
        btnVerGastos.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnVerGastosActionPerformed(evt);
            }
        });

        btnFacturas.setText(resourceMap.getString("btnFacturas.text")); // NOI18N
        btnFacturas.setName("btnFacturas"); // NOI18N
        btnFacturas.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnFacturasActionPerformed(evt);
            }
        });

        GroupLayout jPanel3Layout = new GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnVerVIiajes)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(btnAgregarViaje)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(btnEditViaje)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(btnEliminarViaje)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(btnVerGastos)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(btnFacturas)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(btnBuscarViaje)
                .addContainerGap(35, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(Alignment.LEADING)
            .addGroup(Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(12, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(Alignment.BASELINE)
                    .addComponent(btnVerVIiajes)
                    .addComponent(btnAgregarViaje)
                    .addComponent(btnEditViaje)
                    .addComponent(btnEliminarViaje)
                    .addComponent(btnVerGastos)
                    .addComponent(btnFacturas)
                    .addComponent(btnBuscarViaje))
                .addContainerGap())
        );

        jTabbedPane1.addTab(resourceMap.getString("jPanel3.TabConstraints.tabTitle"), jPanel3); // NOI18N

        tabWork.setName("tabWork"); // NOI18N

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(Alignment.LEADING)
            .addComponent(tabWork, GroupLayout.DEFAULT_SIZE, 1208, Short.MAX_VALUE)
            .addComponent(jTabbedPane1, GroupLayout.DEFAULT_SIZE, 1208, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jTabbedPane1, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(tabWork, GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE))
        );

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(Alignment.LEADING)
            .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(Alignment.LEADING)
            .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarViajeActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnAgregarViajeActionPerformed
        this.saveOrUpdate(0);
    }//GEN-LAST:event_btnAgregarViajeActionPerformed

    private void btnVerVIiajesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnVerVIiajesActionPerformed
        agregaPestanha(gestionViaje.getPanel(), "Ver todos los viajes");
    }//GEN-LAST:event_btnVerVIiajesActionPerformed

    private void btnEditViajeActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnEditViajeActionPerformed
        try {
//            int index = gestionViaje.getSelectedIndex();
            int index = gestionViaje.getSelectedId();
            if (index < 0) {
                throw new Exception();
            } else {
                this.saveOrUpdate(index);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar una viaje existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnEditViajeActionPerformed

    private void btnEliminarViajeActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnEliminarViajeActionPerformed
        try {
            int id = gestionViaje.getSelectedId();
            int result = JOptionPane.showConfirmDialog(this, "Realmente desea eliminar el viaje seleccionado?","Eliminar Viaje", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                gestorViaje.deleteById(id);
                gestionViaje.refresh();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar una viaje existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnEliminarViajeActionPerformed

    private void btnVerGastosActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnVerGastosActionPerformed
        try {
            int i = gestionViaje.getSelectedId();
            manGasto = new ManGasto(i, gestorViaje);
            agregaPestanha(manGasto.getPanel(), "Gastos del viaje " + i);
        } catch (Exception e) {
            System.out.println("E: " + e.getMessage());
            JOptionPane.showMessageDialog(this, "Debe seleccionar una viaje existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnVerGastosActionPerformed

    private void btnFacturasActionPerformed(ActionEvent evt) {//GEN-FIRST:event_btnFacturasActionPerformed
        // TODO add your handling code here:
        try {
            int i = gestionViaje.getSelectedId();
            
            manFactura = new ManFactura(i, gestorViaje);
            agregaPestanha(manFactura.getPanel(), "Facturas del viaje " + i);
        } catch (Exception e) {
            System.out.println("E: " + e.getMessage());
            JOptionPane.showMessageDialog(this, "Debe seleccionar una viaje existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnFacturasActionPerformed

    public void agregaPestanha(JPanel panel, String titulo) {
        this.tabWork.add(titulo, panel);


        this.tabWork.setSelectedIndex(this.tabWork.getTabCount() - 1);
        ButtonTabComponent pestana = new ButtonTabComponent("nano", this.tabWork);


        this.tabWork.setTabComponentAt(this.tabWork.getTabCount() - 1, pestana);


    }

    private void saveOrUpdate(int viajeIndex) {
        if (dialogViajes == null) {
            dialogViajes = new DialogViajes(this, true, viajeIndex, gestorViaje,
                    gestorRuta, gestorPersona, gestorVehiculo);
        } else {
            dialogViajes.setIndex(viajeIndex, true);
        }
        dialogViajes.setLocationRelativeTo(this);
        dialogViajes.setVisible(true);
        if (dialogViajes.isActualizado()) {
            this.gestionViaje.refresh();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ManViaje(true).setVisible(true);


            }
        });


    }

    public JPanel getPanel() {
        return this.jPanel1;
    }

    private void iniciar() {
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorViaje = (GestorViaje) ctx.getBean("gestorViaje");  //new Gesto
        gestorRuta = (GestorRuta) ctx.getBean("gestorRuta");
        gestorPersona = (GestorPersona) ctx.getBean("gestorPersona");
        gestorVehiculo = (GestorVehiculo) ctx.getBean("gestorVehiculo");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JButton btnAgregarViaje;
    private JButton btnBuscarViaje;
    private JButton btnEditViaje;
    private JButton btnEliminarViaje;
    private JButton btnFacturas;
    private JButton btnVerGastos;
    private JButton btnVerVIiajes;
    private JPanel jPanel1;
    private JPanel jPanel3;
    private JTabbedPane jTabbedPane1;
    private JTabbedPane tabWork;
    // End of variables declaration//GEN-END:variables
    private DialogViajes dialogViajes;
    private GestorViaje gestorViaje;
    private GestorRuta gestorRuta;
    private GestorPersona gestorPersona;
    private GestorVehiculo gestorVehiculo;
    private GestionViaje gestionViaje;
    private ManGasto manGasto;
    private ManFactura manFactura;
    ApplicationContext ctx;
}
